<template>
  <el-form inline>
    <div class="flex flex-center">
      <label class="mr-15">线别</label>
      <el-select class="mr-15 flex1" v-model="data.line" placeholder="请选择" @change="afterLineOrGroupChange"
        :disabled="!canSelectLineAndGroup">
        <el-option v-for="l in lineOptions" :key="l.id" :value="l.id" :label="l.line_name"></el-option>
      </el-select>
      <label class="mr-15">工站</label>
      <el-select class="mr-15 flex1" v-model="data.group" placeholder="请选择" @change="afterLineOrGroupChange"
        :disabled="!canSelectLineAndGroup">
        <el-option v-for="l in groupOptions" :key="l.id" :value="l.id" :label="l.group_name"></el-option>
      </el-select>
      <el-button type="info" round @click="clearLineAndGroup">变更</el-button>
    </div>
  </el-form>
</template>
<script>
export default {
  props: {
    functionName: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      lineOptions: [],
      groupOptions: [],
    }
  },
  created() {
    this.init()
  },
  computed: {
    canSelectLineAndGroup: function () {
      return !this.data.line || !this.data.group
    },
  },
  watch: {
    line: () => {
      this.afterLineOrGroupChange()
    },
    group: () => {
      this.afterLineOrGroupChange()
    },
  },
  methods: {
    init() {
      var _tmp = localStorage.getItem(`${this.functionName}-initData`)
      if (_tmp) {
        let tmpObj = JSON.parse(_tmp)
        this.data.line = tmpObj.line
        this.data.group = tmpObj.group
        this.afterLineOrGroupChange()
      }
      this.$request(this.$api.line + 'getlistbypage', { size: 999, page: 1 }, 'get', true)
        .then((r) => {
          this.lineOptions = r.list
        })
        .catch(() => {})
      this.$request(this.$api.group + 'getlistbyuser', { mes_flag: 'Y' }, 'get', true)
        .then((r) => {
          this.groupOptions = r
        })
        .catch(() => {})
    },
    clearLineAndGroup() {
      this.data.line = null
      this.data.group = null
      this.$emit('onClear')
      this.afterLineOrGroupChange()
    },
    afterLineOrGroupChange() {
      var _tmp = localStorage.getItem(`${this.functionName}-initData`)
      localStorage.setItem(
        `${this.functionName}-initData`,
        JSON.stringify({ ...JSON.parse(_tmp), line: this.data.line, group: this.data.group }),
      )
      this.$emit('onChange')
    },
  },
}
</script>